const bcrypt = require('bcryptjs')
const { sequelize } = require('../../core/db');
const { Sequelize,Model } = require('sequelize');
const { NotFound,AuthFailed } = require('../../core/httpException');


class User extends Model{

    // 验证密码是否正确
    static async verifyEmailPassword(email,plainPassword){
        const user = await User.findOne({
            where:{
                email
            }
        })
        if(!user){
            throw new NotFound(['用户不存在'])
        }
        const correct = bcrypt.compareSync(plainPassword,user.password)
        if(!correct){
            throw new AuthFailed(['密码错误'])
        }
        return user
    }

    static async getUserByOpenid(openid){
        const user =  await User.findOne({
            where:{
                openid
            }
        })
        return user
    }
    static async registerByOpenid(openid){
        const user = await User.create({
            openid
        })
        return user
    }
}

User.init({
    id:{
        type:Sequelize.INTEGER,
        primaryKey:true,
        autoIncrement:true
    },
    nickname:Sequelize.STRING,
    email:Sequelize.STRING,
    password:{
        type:Sequelize.STRING,
        set(val){
            const salt = bcrypt.genSaltSync(10);
            const psw = bcrypt.hashSync(val,salt);
            this.setDataValue('password',psw);
        }
    },
    openid:{
        type:Sequelize.STRING(64),
        unique:true
    },
},{
    sequelize,
    tableName:'user'
})

module.exports = { User }